package com.ruoyi.loginrisk.utils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class LoginRiskUtil {

    private static final int MAX_LATENCY = 500; // 最大延迟阈值（ms）
    private static final int IP_CHANGE_RISK_HOUR_THRESHOLD = 1; // 主机地址变化风险小时阈值

    public static Map<String, Object> judgeLoginRisk(String currentIp, String lastIp, Date lastLoginTime, Date currentTime,String lastLocation,String currentLoginLocation,String lastOs,String currentOs) {
        Map<String, Object> result = new HashMap<>();
        boolean isRisky = false;
        String riskReason = "";

        // 主机地址变化判断
        if (lastIp != null && !lastIp.equals(currentIp)) {
            long timeDiff = currentTime.getTime() - lastLoginTime.getTime();
            long hourDiff = timeDiff / (1000 * 60 * 60);
            if (hourDiff <= IP_CHANGE_RISK_HOUR_THRESHOLD) {
                riskReason += "用户ip地址短期内突然变化，";
                isRisky = true;
            }
        }

        //用户IP发生变化
        if (lastLocation != null && !lastLocation.equals(currentLoginLocation)) {
            long timeDiff = currentTime.getTime() - lastLoginTime.getTime();
            long hourDiff = timeDiff / (1000 * 60 * 60);
            if (hourDiff <= IP_CHANGE_RISK_HOUR_THRESHOLD) {
                riskReason += "用户位置短期内突然变化，";
                isRisky = true;
            }
        }

        //用户操作系统发生变化
        if (lastOs != null && !lastOs.equals(currentOs)){
            riskReason += "用户操作系统发生变化，";
            isRisky = true;
        }

        // 去除最后一个逗号
        if (!riskReason.isEmpty()) {
            riskReason = riskReason.substring(0, riskReason.length() - 1);
        } else {
            riskReason = "用户登录状况正常";
        }

        result.put("isRisky", isRisky);
        result.put("riskReason", riskReason);
        return result;
    }
}